#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QDateTime>
#include "maininterface.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    ui->loginPushButton->setStyleSheet(
                "QPushButton {"
                "   background-color: rgb(0,146,209);"
                "   color: white;"  // 同时修改文字颜色
                "border-radius:5px"
                "}"
                "QPushButton:hover {"
                "   background-color: #0000FF;"  // 悬停效果
                "}"
                );


    this->setWindowFlag(Qt::FramelessWindowHint);           //去边框
    //    this->setAttribute(Qt::WA_TranslucentBackground);       //半透明背景
    //    this->setStyleSheet("background-color: white;");  // 设置白色背景


    //更新时间
    loginClockTimer = new QTimer(this);
    connect(loginClockTimer, &QTimer::timeout, this, &Widget::loginUpdateDateTime);
    loginClockTimer->start(1000); // 每秒更新一次时间

    // 初始化键盘进程
    keyboardProcess = new QProcess(this);
    keyboardVisible = false;

    // 连接进程错误信号
    connect(keyboardProcess, &QProcess::errorOccurred, [=](QProcess::ProcessError error) {
        qDebug() << "软键盘进程错误:" << error << keyboardProcess->errorString();
        keyboardVisible = false;
    });

    // 连接进程结束信号
    connect(keyboardProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            [=](int exitCode, QProcess::ExitStatus exitStatus) {
        qDebug() << "软键盘进程结束, 退出码:" << exitCode << "状态:" << exitStatus;
        keyboardVisible = false;
    });

    // 连接输入框的回车信号到登录槽
    connect(ui->usernameLineEdit, &QLineEdit::returnPressed, this, &Widget::on_loginPushButton_clicked);
    connect(ui->passwoedLineEdit, &QLineEdit::returnPressed, this, &Widget::on_loginPushButton_clicked);





}

Widget::~Widget()
{
    // 确保关闭软键盘进程
    if (keyboardProcess && keyboardProcess->state() == QProcess::Running) {
        keyboardProcess->terminate();
        keyboardProcess->waitForFinished();
    }

    delete ui;


}

bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == ui->usernameLineEdit && event->type() == QEvent::FocusIn) {
        // 拦截焦点事件，阻止系统键盘
        return true; // 阻止事件传递
    }
    return QWidget::eventFilter(watched, event);
}

//退出按钮
void Widget::on_exitPushButton_clicked()
{
    QMessageBox quitMes;                        //创建退出弹窗对象
    quitMes.setWindowTitle("关闭界面");          //弹窗标题
    quitMes.setWindowIcon(QIcon(":/widdgetMainInterface/exit.png"));        //设置窗口图标
    quitMes.setIcon(QMessageBox::Warning);      //弹窗图片
    quitMes.setText("请确认是否退出");              //弹窗文本

    quitMes.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);      //设置Ok和Cancle两个按钮
    quitMes.setButtonText(QMessageBox::Ok, "确认");           //Ok改为确认
    quitMes.setButtonText(QMessageBox::Cancel,"取消");        //Cancle改为取消

    int result = quitMes.exec();       //显示信息框等待用户交互
    //如果用户选择了Ok
    if(result == QMessageBox::Ok)
    {
        this->close();          //关闭界面
    }
    else    //用户取消什么都不做
    {

    }

    this->close();
}

//登录按钮
void Widget::on_loginPushButton_clicked()
{
    QString username = ui->usernameLineEdit->text();
    QString password = ui->passwoedLineEdit->text();

    if(username=="Admin" && password=="168168")
    {
        QMessageBox::information(this,"登录","登录成功");

        this->hide();

        mainInterface *mainui = new mainInterface();

        mainui->setGeometry(this->geometry());
        mainui->show();
    }
    else
    {
        QMessageBox::warning(this,"失败","登录失败");
    }
}

//更新时间
void Widget::loginUpdateDateTime()
{
    QDateTime currentTime = QDateTime::currentDateTime();
    QString loginymdtimeStr = currentTime.toString("yyyy年MM月dd日");
    QString loginhmstimeStr = currentTime.toString("hh:mm:ss");

    ui->currentTimeymdlLabel->setText(loginymdtimeStr);
    ui->currentTimehmsLabel->setText(loginhmstimeStr);

}

//软键盘
void Widget::on_pushButton_clicked()
{
    if (!keyboardVisible) {
        bool started = false;

        // 方法1: 使用QProcess尝试启动
        keyboardProcess->start("osk.exe");
        if (keyboardProcess->waitForStarted(1500)) {
            keyboardVisible = true;
            started = true;
            qDebug() << "软键盘已启动 (QProcess)";
        }

        // 方法2: 如果QProcess失败，尝试完整路径
        if (!started) {
            QString oskPath = "C:\\Windows\\System32\\osk.exe";
            keyboardProcess->start(oskPath);
            if (keyboardProcess->waitForStarted(1500)) {
                keyboardVisible = true;
                started = true;
                qDebug() << "软键盘已启动 (完整路径)";
            }
        }

        // 方法3: 如果前两种方法失败，使用Windows API绕过重定向
        if (!started) {
            qDebug() << "尝试使用Windows API启动软键盘";

            // 禁用文件系统重定向
            PVOID oldValue;
            Wow64DisableWow64FsRedirection(&oldValue);

            // 使用ShellExecute启动
            HINSTANCE result = ShellExecuteW(
                        0,
                        L"open",
                        L"osk.exe",
                        0,
                        0,
                        SW_SHOWNORMAL
                        );

            // 恢复文件系统重定向
            Wow64RevertWow64FsRedirection(oldValue);

            if (reinterpret_cast<int>(result) > 32) {
                keyboardVisible = true;
                started = true;
                qDebug() << "软键盘已启动 (Windows API)";
            } else {
                qDebug() << "Windows API启动失败, 错误码:" << reinterpret_cast<int>(result);
            }
        }

        if (!started) {
            QMessageBox::warning(this, "错误", "无法启动软键盘。请确保系统支持屏幕键盘(osk.exe)。");
        }
        else {
            // 关闭软键盘
            if (keyboardProcess->state() == QProcess::Running) {
                keyboardProcess->terminate();
                if (keyboardProcess->waitForFinished(1000)) {
                    keyboardVisible = false;
                    qDebug() << "软键盘已关闭";
                } else {
                    qDebug() << "无法关闭软键盘:" << keyboardProcess->errorString();
                }
            } else {
                keyboardVisible = false;
            }
        }
    }
}

